import { Component, Inject } from '@angular/core';
import { IonicPage, App, NavController, ModalController } from 'ionic-angular';

import { Register } from '../../../providers/entity/user.model';
import { Subscription } from 'rxjs/Subscription';

// util service
import { AlertService } from '../../../providers/utils/alert.service';
/**
 * 找回密码
 */
@IonicPage()
@Component({
  selector: 'page-forget',
  templateUrl: 'forget.html',
})
export class ForgetPage {

  // 注册
  private forget: Register = {
    username: '',
    password: '',
    msgCode: '',
  };
  // 是否显示密码
  private switchover: any = {
    type: 'password',
    status: true
  };

  // 定时器
  private timer: any;
  // 倒计时
  private countdown: number= 0;
  private authSubscription: Subscription;

  constructor(
    @Inject('auth') private authService,
    private alertCtrl: AlertService,
    private appCtrl: App,
    private navCtrl: NavController,
    private modalCtrl: ModalController,
  )
  {}

  /*** 页面进入
   * */
  ionViewWillEnter()
  {
    this.initForgetUsernameWhenLogin();
  }
  /*** 在登录后填充表单忘记密码
  * */
  initForgetUsernameWhenLogin()
  {
    this.authSubscription= this.authService.getAuth()
      .filter(auth=> auth.login!== null)
      .map(auth=> auth.login.username)
      .subscribe(username=> {
        this.forget.username = username;
      });
  }

  /*** 页面离开
   * */
  ionViewWillLeave()
  {
    if(typeof this.authSubscription !== 'undefined')
      this.authSubscription.unsubscribe();
  }

  /*** 打开定时器
   * */
  public startInterval(): void
  {
    this.timer = setInterval(()=>{
      this.countdown--;
      if(this.countdown === 0)
      {
        clearInterval(this.timer);
        this.timer = null;
      }
    },1000);
  }

  /*** 清除昵称
   * */
  public clearUserName(): void
  {
    this.forget.username='';
  }

  /*** 切换密码显示方式
   * */
  public switchoverPassword(obj: any): void
  {
    if(!obj.type) return;
    this.switchover = {
      type: obj.type==='text'? 'password': 'text',
      status: !obj.status
    }

  }

  /*** 清除输入
   * */
  public clearMsgCode()
  {
    this.forget.msgCode = '';
  }

  /** 执行发送验证码
   * */
  public executeGetAgain(): void
  {
    if(!this.forget.username)
    {
      this.alertCtrl.createAgreeAlert('手机号不为空');
      return;
    }
    this.countdown= 60 ;
    this.startInterval();
    this.authService.sendMsgCodeWhenForget(this.forget);
  }

  /*** 去验证更新密码
   * */
  public executeUpdatePassword() {
    this.authService.getBackPassword(this.forget, this.appCtrl, this.navCtrl, this.modalCtrl);
  }
}
